// 现⿏标放在头像框，出现下拉框
const user = document.querySelector('.user')
function frameenter() {
  user.nextElementSibling.style.display = 'block'
  user.nextElementSibling.nextElementSibling.style.display = 'block'
}
function frameleave() {
  user.nextElementSibling.style.display = 'none'
  user.nextElementSibling.nextElementSibling.style.display = 'none'
}
user.addEventListener('mouseenter', frameenter)
user.addEventListener('mouseleave', frameleave)
user.nextElementSibling.addEventListener('mouseenter', frameenter)
user.nextElementSibling.addEventListener('mouseleave', frameleave)
user.nextElementSibling.nextElementSibling.addEventListener('mouseenter', frameenter)
user.nextElementSibling.nextElementSibling.addEventListener('mouseleave', frameleave)

// 封装函数
function myAxios(config) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest()
    if (config.params) {
      const paramsObj = new URLSearchParams(config.params)
      const queryString = paramsObj.toString()
      config.url += `?${queryString}`
    }
    xhr.open(config.method || 'get', config.url)
    xhr.addEventListener('loadend', () => {
      if (xhr.status >= 200 && xhr.status < 300) {
        try {
          resolve(JSON.parse(xhr.response))
        } catch (error) {
          reject(error)
        }
      } else {
        reject(new Error(xhr.response))
      }
    })
    if (config.headers) {
      Object.keys(config.headers).forEach(key => {
        xhr.setRequestHeader(key, config.headers[key])
      })
    }
    if (config.data instanceof FormData) {
      xhr.send(config.data)
    } else if (config.data) {
      xhr.setRequestHeader('Content-Type', 'application/json')
      xhr.send(JSON.stringify(config.data))
    } else {
      xhr.send()
    }
  })
}

let situation = false
const box = document.querySelector('.background-shadow')
const zhreg = /^[a-zA-Z0-9_-]{6,}$/
const pwreg = /^(?=.*[a-z])[a-zA-Z0-9_]{6,}$/

// 点击头像，出现登录模态框
function openBox() {
  box.style.display = 'block'
}
user.addEventListener('click', openBox)

// 关闭模态框按钮
function closeBox() {
  box.style.display = 'none'
}
// 登录注册逻辑
const performAction = () => {
  if (situation) {
    if (zhreg.test(document.querySelector('.username').value) && pwreg.test(document.querySelector('.password').value)) {
      myAxios({
        url: 'https://blog.zifeiyu.love/user/register',
        method: 'post',
        data: {
          username: document.querySelector('.username').value,
          password: document.querySelector('.password').value
        }
      }).then(() => {
        alert('您已注册成功')
      })
    } else {
      alert('注册不合法,账号密码至少6位,密码至少含一个小写字母')
    }
  } else {
    myAxios({
      url: 'https://blog.zifeiyu.love/user/login',
      params: {
        username: document.querySelector('.username').value,
        password: document.querySelector('.password').value,
      }
    }).then((result) => {
      box.style.display = 'none'
      myAxios({
        url: 'https://blog.zifeiyu.love/info/query',
        headers: {
          token: localStorage.getItem('token')
        }
      }).then(result => {
        document.querySelector('.user a img').src = result.data.avatar
      })
      localStorage.setItem('token', result.data.tokenValue)
    }).catch(() => {
      alert('账户或者密码有误')
    })
  }
}
// 重新监听DOM
function setupEventListeners() {
  const closebtn = document.querySelector('.icon-shanchu')
  if (closebtn) {
    closebtn.removeEventListener('click', closeBox)
  }
  closebtn.addEventListener('click', closeBox)
  const loginBtn = document.querySelector('.login')
  if (loginBtn) {
    loginBtn.removeEventListener('click', performAction)
  }
  loginBtn.addEventListener('click', performAction)
}
setupEventListeners()

// 注册登录模态框切换
function changeMode() {
  document.querySelector('.changeMode').addEventListener('click', () => {
    situation = !situation
    if (situation) {
      box.innerHTML = `
        <div class="box">
          <header class="box-header">
            <i class="iconfont icon-xiangzuolajiantou"></i>
            <span>QQ账号注册</span>
            <i class="iconfont icon-shanchu"></i>
          </header>
          <h3>注册后才能观看视频哟</h3>
          <div class="box-body">
            <article>
              <h4>账号注册</h4>
              <p>推荐使用<a href="#">一键注册</a>,防止盗号</p>
              <input type="text" placeholder="支持QQ号/邮箱/手机号注册" class="username">
              <input type="password" placeholder="请输入密码" class="password">
              <button class="login">注册</button>
              <div class="function">
                <a href="#">找回密码</a>
                <a href="#" class="changeMode">登录账号</a>
                <a href="#">意见反馈</a>
              </div>
            </article>
            <aside>
              <ul>
                <li>
                  <input type="checkbox" id="all" checked>
                  <label for="all">全选 <a href="index.html">腾讯视频</a> 将获取以下权限:</label>
                </li>
                <li>
                  <input type="checkbox" id="information" checked disabled>
                  <label for="information">使用你的QQ头像、昵称信息</label>
                </li>
              </ul>
              <p>授权即同意<a href="#">服务协议</a>和<a href="#">QQ隐私保护指引</a></p>
            </aside>
          </div>
        </div>`
    } else {
      box.innerHTML = `
        <div class="box">
          <header class="box-header">
            <i class="iconfont icon-xiangzuolajiantou"></i>
            <span>QQ账号登录</span>
            <i class="iconfont icon-shanchu"></i>
          </header>
          <h3>登录后高清播放更流畅</h3>
          <div class="box-body">
            <article>
              <h4>密码登录</h4>
              <p>推荐使用<a href="#">快捷登录</a>,防止盗号</p>
              <input type="text" placeholder="支持QQ号/邮箱/手机号登录" class="username">
              <input type="password" placeholder="请输入密码" class="password">
              <button class="login">登录</button>
              <div class="function">
                <a href="#">找回密码</a>
                <a href="#" class="changeMode">注册账号</a>
                <a href="#">意见反馈</a>
              </div>
            </article>
            <aside>
              <ul>
                <li>
                  <input type="checkbox" id="all" checked>
                  <label for="all">全选 <a href="index.html">腾讯视频</a> 将获取以下权限:</label>
                </li>
                <li>
                  <input type="checkbox" id="information" checked disabled>
                  <label for="information">使用你的QQ头像、昵称信息</label>
                </li>
              </ul>
              <p>授权即同意<a href="#">服务协议</a>和<a href="#">QQ隐私保护指引</a></p>
            </aside>
          </div>
        </div>`
    }
    setupEventListeners()
    changeMode()
  })
}
changeMode()

// 登录后添删功能
if (localStorage.getItem('token')) {
  myAxios({
    url: 'https://blog.zifeiyu.love/info/query',
    headers: {
      token: localStorage.getItem('token')
    }
  }).then(result => {
    document.querySelector('.user a img').src = result.data.avatar
  })
  user.removeEventListener('mouseenter', frameenter)
  user.removeEventListener('mouseleave', frameleave)
  user.removeEventListener('click', openBox)
  user.addEventListener('click', () => {
    setTimeout(() => {
      location.href = 'person.html'
    }, 2000)
  })
}

// 收藏
const collectBox = document.createElement('div')
collectBox.classList.add('tip')
document.querySelector('.tencent').appendChild(collectBox)

// tab栏切换
function allClick() {
  myAxios({
    url: 'https://blog.zifeiyu.love/video/random',
    params: {
      size: '8',
    },
    headers: {
      token: localStorage.getItem('token')
    }
  }).then(result => {
    let str = ''
    result.data.forEach(item => {
      const { cover, id, name, tag, brief } = item
      str += `
          <div class="bd-item" data-id="${id}">
            <div class="bd-element">
              <div class="bd-img">
                <img src="${cover}" alt="">
                <span class="bd-type">独播</span><span class="bd-episode"></span>
              </div>
              <video class="hidden-video" src="" data-id="" controls disablepictureinpicture autoplay loop muted controlslist="nodownload noremoteplayback noplaybackrate"></video>
            </div>
            <div class="bd-text">
              <div class="bd-intro">
                <span class="work-title">${name}</span>
                <span class="work-text">"${brief}"</span>
              </div>
              <div class="video-intro">
                <span class="work-title">${name}</span>
                <span class="work-text">${tag}</span>
                <span class="work-text">"${brief}"</span>
                <div class="shoucang">
                  <i class="iconfont icon-menu-left"></i>
                  <span class="subscribe">追</span>
                  <span class="subscribe-active">在追</span>
                </div>
              </div>
            </div>
          </div>
        `
      document.querySelector('.text-bd').innerHTML = str
    })

    // 鼠标悬停播放视频
    const items = document.querySelectorAll('.bd-item')
    items.forEach((item) => {
      const itemChild = item.querySelectorAll('*')
      let debounceTimer
      let throttleTimer
      let isMouseEntered = false
      item.addEventListener('mouseenter', () => {
        clearTimeout(debounceTimer)
        debounceTimer = setTimeout(() => {
          if (isMouseEntered) {
            myAxios({
              url: 'https://blog.zifeiyu.love/video/queryEpisode',
              params: {
                id: item.dataset.id
              },
              headers: {
                token: localStorage.getItem('token')
              }
            }).then(result => {
              for (let i = 0; i < itemChild.length; i++) {
                if (itemChild[i].classList.contains('hidden-video')) {
                  itemChild[i].style.display = 'block'
                  itemChild[i].src = result.data[0].url
                  itemChild[i].dataset.id = result.data[0].id
                }
                if (itemChild[i].classList.contains('video-intro')) {
                  itemChild[i].style.opacity = '1'
                }
              }
            })
          }
        }, 500)
        isMouseEntered = true
      })
      item.addEventListener('mouseleave', () => {
        if (!throttleTimer) {
          throttleTimer = setTimeout(() => {
            throttleTimer = null
            for (let i = 0; i < itemChild.length; i++) {
              if (itemChild[i].classList.contains('hidden-video')) {
                itemChild[i].style.display = 'none'
              }
              if (itemChild[i].classList.contains('video-intro')) {
                itemChild[i].style.opacity = '0'
              }
            }
            isMouseEntered = false
          }, 300)
        }
      })

      //收藏
      let flag = false
      for (let i = 0; i < itemChild.length; i++) {
        if (itemChild[i].classList.contains('shoucang')) {
          itemChild[i].addEventListener('click', () => {
            if (localStorage.getItem('token')) {
              myAxios({
                url: 'https://blog.zifeiyu.love/video/star',
                params: {
                  id: item.dataset.id,
                },
                headers: {
                  token: localStorage.getItem('token')
                }
              }).then(result => {
                if (!flag) {
                  itemChild[i].children[0].style.display = 'none'
                  itemChild[i].children[1].style.display = 'none'
                  itemChild[i].children[2].style.display = 'block'
                  flag = true
                } else {
                  itemChild[i].children[0].style.display = 'block'
                  itemChild[i].children[1].style.display = 'block'
                  itemChild[i].children[2].style.display = 'none'
                  flag = false
                }
                collectBox.innerHTML = result.data
                collectBox.style.display = 'block'
                setTimeout(() => {
                  collectBox.style.display = 'none'
                }, 2000)
              })
            } else {
              openBox()
            }
          })
        }
      }
    })

    // 视频触底无限刷新
    let n = 1
    window.addEventListener('scroll', () => {
      const windowH = document.documentElement.scrollHeight - 1
      const documentH = document.documentElement.clientHeight
      const scrollH = document.documentElement.scrollTop
      if (scrollH + documentH >= windowH) {
        myAxios({
          url: 'https://blog.zifeiyu.love/video/search',
          params: {
            type: '',
            name: '',
            page: n,
            size: '8'
          },
          headers: {
            token: localStorage.getItem('token')
          }
        }).then(result => {
          result.data.records.forEach(item => {
            const { cover, id, name, tag, brief } = item
            str += `
          <div class="bd-item" data-id="${id}">
            <div class="bd-element">
              <div class="bd-img">
                <img src="${cover}" alt="">
                <span class="bd-type">独播</span><span class="bd-episode"></span>
              </div>
              <video class="hidden-video" src="" autoplay loop muted></video>
            </div>
            <div class="bd-text">
              <div class="bd-intro">
                <span class="work-title">${name}</span>
                <span class="work-text">"${brief}"</span>
              </div>
              <div class="video-intro">
                <span class="work-title">${name}</span>
                <span class="work-text">${tag}</span>
                <span class="work-text">"${brief}"</span>
                <div class="shoucang">
                  <i class="iconfont icon-menu-left"></i>
                  <span class="subscribe">追</span>
                  <span class="subscribe-active">在追</span>
                </div>
              </div>
            </div>
          </div>
        `
            document.querySelector('.text-bd').innerHTML = str
          })
          n++
        })
      }
    })
  })
}
// 页面一刷新就更新
allClick()

function tvClick() {
  myAxios({
    url: 'https://blog.zifeiyu.love/video/search',
    params: {
      type: '电视剧',
      name: '',
      page: '1',
      size: '8',
    },
    headers: {
      token: localStorage.getItem('token')
    }
  }).then(result => {
    let str = ''
    result.data.records.forEach(item => {
      const { cover, id, name, tag, brief, allCount } = item
      str += `
          <div class="bd-item" data-id="${id}">
            <div class="bd-element">
              <div class="bd-img">
                <img src="${cover}" alt="">
                <span class="bd-type">独播</span><span class="bd-episode">更新至${allCount}集</span>
              </div>
              <video class="hidden-video" src="" autoplay loop muted></video>
            </div>
            <div class="bd-text">
              <div class="bd-intro">
                <span class="work-title">${name}</span>
                <span class="work-text">"${brief}"</span>
              </div>
              <div class="video-intro">
                <span class="work-title">${name}</span>
                <span class="work-text">${tag}</span>
                <span class="work-text">"${brief}"</span>
                <div class="shoucang">
                  <i class="iconfont icon-menu-left"></i>
                  <span class="subscribe">追</span>
                  <span class="subscribe-active">在追</span>
                </div>
              </div>
            </div>
          </div>
        `
      document.querySelector('.text-bd').innerHTML = str
    })
  })
}
function filmClick() {
  myAxios({
    url: 'https://blog.zifeiyu.love/video/search',
    params: {
      type: '电影',
      name: '',
      page: '1',
      size: '8',
    },
    headers: {
      token: localStorage.getItem('token')
    }
  }).then(result => {
    let str = ''
    result.data.records.forEach(item => {
      const { cover, id, name, tag, brief, mark } = item
      str += `
          <div class="bd-item" data-id="${id}">
            <div class="bd-element">
              <div class="bd-img">
                <img src="${cover}" alt="">
                <span class="bd-type">独播</span><span class="bd-episode">${mark}分</span>
              </div>
              <video class="hidden-video" src="" autoplay loop muted></video>
            </div>
            <div class="bd-text">
              <div class="bd-intro">
                <span class="work-title">${name}</span>
                <span class="work-text">"${brief}"</span>
              </div>
              <div class="video-intro">
                <span class="work-title">${name}</span>
                <span class="work-text">${tag}</span>
                <span class="work-text">"${brief}"</span>
                <div class="shoucang">
                  <i class="iconfont icon-menu-left"></i>
                  <span class="subscribe">追</span>
                  <span class="subscribe-active">在追</span>
                </div>
              </div>
            </div>
          </div>
        `
      document.querySelector('.text-bd').innerHTML = str
    })
  })
}

const btn = document.querySelector('.hd-type')
btn.addEventListener('click', e => {
  e.preventDefault()
  if (e.target.tagName === 'A') {
    if (e.target.dataset.id === '0') {
      allClick()
    } else if (e.target.dataset.id === '1') {
      tvClick()
    } else if (e.target.dataset.id === '3') {
      filmClick()
    }
    document.querySelector('.hd-type .active').classList.remove('active')
    e.target.classList.add('active')
  }
})

// 换一换
document.querySelector('.change').addEventListener('click', () => {
  allClick()
})

// 滑动tab栏透明度变化
const header = document.querySelector('.app-top')
const bg = document.querySelector('.background')
window.addEventListener('scroll', () => {
  const n = document.documentElement.scrollTop
  if (n >= bg.offsetHeight) {
    header.style.backgroundColor = 'rgba(0,0,0)'
    header.style.opacity = '1'
  } else {
    header.style.backgroundColor = ''
    header.style.opacity = '.7'
  }
})
// 更换背景板
const backgroundData = [
  {
    bcg: '../images/background-box/01/background.jpg',
    logo: '../images/background-box/01/introduce.png',
    type: '陈晓 童瑶 婚姻生活',
    text: '"陈晓童瑶首搭守护小日子"',
  },
  {
    bcg: '../images/background-box/02/background.jpg',
    logo: '../images/background-box/02/introduce.png',
    type: '江疏影 杨采钰 都市生活',
    text: '五美全员回归上演终极复仇',
  },
  {
    bcg: '../images/background-box/03/background.jpg',
    logo: '../images/background-box/03/introduce.png',
    type: '邓超 陈赫 游戏节目',
    text: '猫鼠游戏2.0:邓超范志毅猛咬鹿晗大腿',
  },
  {
    bcg: '../images/background-box/04/background.jpg',
    logo: '../images/background-box/04/introduce.png',
    type: '奇幻冒险 玄幻修真',
    text: '龙皓晨进入选主试炼与最强圣卫对决！',
  },
  {
    bcg: '../images/background-box/05/background.jpg',
    logo: '../images/background-box/05/introduce.png',
    type: '赵丽颖 林更新 仙侠玄幻',
    text: '赵丽颖林更新甜虐仙凡恋',
  }
]
const intro = document.querySelector('.introduce')
const work = document.querySelectorAll('.work')
work.forEach(item => {
  item.children[0].addEventListener('mouseenter', function (e) {
    item.classList.add('active')
    intro.innerHTML = `
        <div class="introduce-img">
          <img src="${backgroundData[e.target.dataset.id].logo}" alt="">
        </div>
        <span class="introduce-type">${backgroundData[e.target.dataset.id].type}</span>
        <span class="introduce-text">${backgroundData[e.target.dataset.id].text}</span>
        <div class="introduce-bottom">
          <div class="button">
            <span>播放正片</span>
          </div>
          <div class="voice">
            <i class="iconfont icon-jingyin"></i>
          </div>
        </div>
        `
    intro.parentNode.style.background = `url(${backgroundData[e.target.dataset.id].bcg}) no-repeat`
    intro.parentNode.style.backgroundSize = 'cover'
  })
  item.children[0].addEventListener('mouseleave', function () {
    item.classList.remove('active')
  })
})

// 搜索框跳转视频详情页
document.querySelector('.search-input').addEventListener('input', (e) => {
  if (e.target.value.trim()) {
    myAxios({
      url: 'https://blog.zifeiyu.love/video/search',
      params: {
        type: '',
        name: e.target.value,
        page: 1,
        size: 10
      },
      headers: {
        token: localStorage.getItem('token')
      }
    }).then(result => {
      const liStr = result.data.records.map(item => {
        return `<li><span style="color:#fff;">《${item.name}》</span><span style="color:#fff;">${item.brief}</span><span>${item.type}</span></li>`
      }).join('')
      document.querySelector('.smartbox').innerHTML = liStr
      // 搜索历史记录
      history('liStr', liStr)
      const LiStr = result.data.records.map(item => {
        return `${item.id}`
      }).join('')
      history('ids', LiStr)
      localStorage.setItem('id', result.data.records[0].id)
    })
  }
})

// 搜索历史记录
function history(key, value) {
  let inputValue = value
  let inputHis = JSON.parse(localStorage.getItem(key)) || []
  if (inputValue || inputValue.length > 0) {
    if (inputHis.includes(inputValue)) {
      inputHis.splice(inputHis.indexOf(inputValue), 1)
      inputHis.unshift(inputValue)
      localStorage.setItem(key, JSON.stringify(inputHis))
    } else {
      inputHis.unshift(inputValue)
      localStorage.setItem(key, JSON.stringify(inputHis))
    }
  }
}
document.querySelector('.search-input').addEventListener('focus', () => {
  document.querySelector('.smartbox').innerHTML = JSON.parse(localStorage.getItem('liStr')).join('')
})
document.querySelector('.smartbox').addEventListener('click', (e) => {
  const li = e.target.closest('li')
  if (li) {
    location.href = 'detail.html'
  }
})
